import { createRoot } from 'react-dom/client';
import { LoadingOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import './style.css';

const LoadingStyle = styled.div`
	height: 100%;
	color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;

	.loading-text {
		margin-top: 10px;
		color: #fff;
		text-align: center;
	}
`;

export class Loading {
	private text: string;
	private body: HTMLElement;
	private divContent: HTMLDivElement;

	constructor(text?: string) {
		this.text = text ?? '加载中...';
		this.body = document.body;
	}

	loading = () => {
		const ele = document.createElement('div');
		ele.id = 'full-loading-dom';
		const LoadingContent = (
			<LoadingStyle>
				<div className="loading-fullscreen">
					<LoadingOutlined style={{ fontSize: '50px' }} />
					<div className="loading-text">{this.text ?? '加载中...'}</div>
				</div>
			</LoadingStyle>
		);
		createRoot(ele).render(LoadingContent);
		this.divContent = ele;
		this.body.appendChild(this.divContent);
		this.divContent.classList.add('full-loading-into');
		setTimeout(() => {
			this.divContent.classList.add('full-loading-active');
		}, 0);
	};

	close = () => {
		this.divContent.classList.remove('full-loading-active');
		setTimeout(() => {
			this.divContent.remove();
		}, 200);
	};

	hasLoading = () => Boolean(this.body.children.namedItem('full-loading-dom'));
}

const FullscreenLoading = new Loading();

export default FullscreenLoading;
